<template>
    <div class="app-container">
        <el-form :inline="true" ref="queryRef" label-position="right" :model="params" label-width="200px">
            <div class="form-inline">
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="维护人：" class="form-item" prop="userName">
                            <el-input v-model="params.userName" placeholder="请输入" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="维护时间:">
                            <el-col :span="11">
                                <el-form-item prop="createStartTime">
                                    <el-date-picker clearable v-model="params.createStartTime" type="date"
                                        placeholder="开始时间" value-format="YYYY-MM-DD" :disabled-date="startDisableDate"
                                        style="width: 100%" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="1" class="text-center">
                                <span class="text-gray-500">-</span>
                            </el-col>
                            <el-col :span="11">
                                <el-form-item prop="createEndTime">
                                    <el-date-picker clearable v-model="params.createEndTime" type="date" placeholder="结束时间"
                                        value-format="YYYY-MM-DD" :disabled-date="endDisableDate" style="width: 100%" />
                                </el-form-item>
                            </el-col>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row justify="center">
                    <!-- <el-col :span="11">
                        <el-form-item label="维护人所属单位：" class="form-item" prop="maintainerUnit">
                            <el-input v-model="params.maintainerUnit" placeholder="" clearable />
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="11">
                        <!-- <el-form-item label="结构类型：">
                            <el-form-item prop="structureType">
                                <el-select v-model="params.structureType" placeholder="请选择" class="form-select" clearable>
                                    <el-option v-for="item in structureTypeOptions" :key="item.value"
                                        :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-form-item> -->
						<el-form-item label="结构类型：">
							<el-col :span="11">
								<el-form-item prop="structureType">
									<el-select v-model="params.structureType" placeholder="请选择" class="form-select"
										@change="structureTypeChange" clearable>
										<el-option v-for="item in structureTypeOptions" :key="item.value"
											:label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
							<el-col :span="11">
								<el-form-item prop="structureType1">
									<el-select v-model="params.structureType1" placeholder="请选择" class="form-select"
										clearable>
										<el-option v-for="item in structureType1Options" :key="item.value"
											:label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="区域：" class="form-item" prop="region">
                            <el-form-item prop="province" style="width:120px;margin-right:10px;">
                                <el-select v-model="params.province" placeholder="请选择省" @change="chooseProvince" clearable
                                    value-key="id">
                                    <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="city" style="width:120px;margin-right:10px;">
                                <el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable
                                    value-key="id">
                                    <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="county" style="width:120px;">
                                <el-select v-model="params.county" placeholder="请选择县" @change="chooseCounty" clearable
                                    value-key="id">
                                    <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="设防情况：" class="form-item" prop="fortification">
                            <el-select v-model="params.fortification" placeholder="请选择" class="form-select" clearable>
                                <el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="建造年代：" class="form-item" prop="years">
                            <el-select v-model="params.years" placeholder="请选择" class="form-select" clearable>
                                <el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="用途：">
                            <el-col :span="11">
                                <el-form-item prop="purpose">
                                    <el-select v-model="params.purpose" placeholder="请选择" class="form-select"
                                        @change="useChange" clearable>
                                        <el-option v-for="item in useOptions" :key="item.value" :label="item.label"
                                            :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="1" class="text-center">
                                <span class="text-gray-500">-</span>
                            </el-col>
                            <el-col :span="11">
                                <el-form-item prop="purpose1">
                                    <el-select v-model="params.purpose1" placeholder="请选择" class="form-select" clearable>
                                        <el-option v-for="item in use1Options" :key="item.value" :label="item.label"
                                            :value="item.value">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-form-item>
                    </el-col>
                    <el-col :span='11'></el-col>
                </el-row>

                <el-row justify="end">
                    <el-form-item class="bottom-button">
                        <el-button type="primary" @click="onRecalculate">重新计算</el-button>
                        <el-button type="primary" @click="onExport">导出</el-button>
                        <el-button type="primary" @click="onViewResults">查看计算结果</el-button>
                        <el-button type="primary" @click="onSearch">查询</el-button>
                        <el-button type="primary" @click="onRest">重置</el-button>
                    </el-form-item>
                </el-row>
            </div>
        </el-form>

        <div class="table-wrapper">
            <el-table class="listTable" ref="multipleTableRef" border :data="tableData" style="width: 100%"
                @selection-change="handleSelectionChange" @row-click="rowClick"
                :cell-style="{ border: '1px solid #e5ebf7' }"
                :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">

                <el-table-column type="selection" width="55" label="序号" />
                <el-table-column prop="number" header-align="center" align="center" label="编号">
                    <template #default="scope">
                        <el-button link type="text" size="small" @click.prevent="viewProject(scope.row)">
                            {{ scope.row.number }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="region" header-align="center" align="center" label="区域" />
                <el-table-column prop="st" header-align="center" align="center" label="结构类型" />
                <el-table-column prop="years" header-align="center" align="center" label="建造年代" width="100" />
                <el-table-column prop="fortification" header-align="center" align="center" label="设防情况" width="100" />
                <el-table-column prop="calculateOrNot" header-align="center" align="center" label="是否已计算" width="100">
                    <template #default="scope">{{ scope.row.calculateOrNot == '1' ? '是' : '否' }}</template>
                </el-table-column>
                <el-table-column prop="userName" header-align="center" align="center" label="维护人" />
                <el-table-column prop="createTime" header-align="center" align="center" label="维护时间" width="160">
                    <template #default="scope">{{ proxy.parseTime(scope.row.createTime) }}</template>
                </el-table-column>
                <el-table-column prop="use" header-align="center" align="center" label="用途">
                    <template #default="scope">
                        <span>{{ getUseByOptions(scope.row.purpose) }}-{{ getChildUseByOptions(scope.row.purpose,
                            scope.row.purpose1)
                        }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="操作" fixed="right" width="80">
                    <template #default="scope">
                        <el-button type="text" size="small" @click="onDelete(scope.row)">删除</el-button>
                        <el-button type="text" size="small" @click="onModify(scope.row)">修改</el-button>
                    </template>
                </el-table-column> -->
            </el-table>
            <div class="paging">
                <el-pagination background v-model:current-page="queryPagination.pageNo" :layout="layout"
                    :page-size="queryPagination.pageSize" :total="queryPagination.total"
                    @current-change="handleCurrentChange" @size-change="handleSizeChange" />
            </div>
        </div>
    </div>
</template>
 
<script setup>
import { reactive, toRefs } from "vue";
// 引入store
import useUserStore from '@/store/modules/user';
import useDictStore from '@/store/modules/dict';
// 自定义导出
import { downloadFile } from '@/utils/ruoyi';
// 引入接口
import {
    queryHighriseApi,// 分页查询
    highriseExportApi,//导出
    highriseCalculationApi,//计算
} from "@/api/buildingVulnerAnalysis/buildingVulnerAnalysis.js";
// 引入行政区划接口
import { getProvince, getChildArea } from "@/api/system/division";

// 获取当前实例
const { proxy } = getCurrentInstance();
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 全局路由对象
const router = useRouter();

// 用户名
const userName = computed(() => userStore.name || '');
// 所属机构名称
const orgName = computed(() => userStore.orgName || '');

const data = reactive({
    // 表单参数
    params: {
        // userName: userName.value, //维护人
        userName: '', //维护人
        // maintainerUnit: orgName.value, //维护人所属单位
        maintainerUnit: '', //维护人所属单位
        createStartTime: '', //维护开始时间
        createEndTime: '', //维护结束时间
        structureType: '', //结构类型
		structureType1: '',
        //intensity: "", //烈度
        //damage: "", //破坏状态
        fortification: '', //设防情况
        years: '', //建造年代
        region: '', //区域
        purpose: '', //用途
        purpose1: '',
        province: '', //省
        city: '', //市
        county: '' //区县
    },
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	// 年份
	yearsOptions: dictStore.yearsOptions || [],
	// 结构类型
	structureTypeOptions: dictStore.structureTypeOptions3 || [],
	structureType1Options: [],
	// 用途
	useOptions: dictStore.useOptions || [],
    use1Options: [],
    //表格
    tableData: [],
    // 表格选中数据
    multipleSelection: [],
    // 当前行数据
    curTableRow: {},

    // 分页面板控件
    layout: ' prev, pager, next, jumper, sizes, total',
    // 分页参数
    queryPagination: {
        pageNo: 1,
        pageSize: 10,
        total: 0
    }
});

const {
    // 表单参数
    params,
    // 烈度选项
    intensityOptions,
    // 设防情况选项
    fortificationOptions,
    // 建造年代选项
    yearsOptions,
    // 结构类型选项
    structureTypeOptions,
	structureType1Options,
    // 用途选项
    useOptions,
    use1Options,
    // 表格数据
    tableData,
    // 表格选中数据
    multipleSelection,
    // 当前行数据
    curTableRow,
    // 分页数据
    queryPagination,
    // 分页工具栏
    layout
} = toRefs(data);

/* 
    根据值获取用途
    params: {
        key: 值
    }
 */
function getUseByOptions(key) {
    const use = useOptions.value.find(item => item.value == key);
    return use ? use.label || '' : '';
}
/* 
    根据值获取子用途
    params: {
        key1: 一级值
        key2: 二级值
    }
 */
function getChildUseByOptions(key1, key2) {
    const use = useOptions.value.find(item => item.value == key1);
    let childUse = {};
    if (use && use.children) {
        childUse = use.children.find(item => item.value == key2);
    }
    return childUse ? childUse.label || '' : '';
}

// 行政区划
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
/** 获取省列表 */
function getProvinceData() {
    getProvince().then((response) => {
        provinceData.value = response.data;
    });
}
// 选择省份
function chooseProvince(value) {
    params.value.city = null;
    params.value.county = null;
    params.value.province = value.name;
    cityData.value = [];
    areaData.value = [];
    getChildArea(value.id).then(response => {
        cityData.value = response.data;
    });
}
// 选择城市
function chooseCity(value) {
    params.value.city = value.name;
    params.value.county = null;
    areaData.value = [];
    getChildArea(value.id).then((response) => {
        areaData.value = response.data;
    });
}
// 选择区县
function chooseCounty(value) {
    params.value.county = value.name;
}

// 开始时间禁用区间
const startDisableDate = (time) => {
    let endDateVal = params.value.createEndTime
    if (endDateVal) {
        return time.getTime() > new Date(endDateVal).getTime()
    }
}
// 结束时间禁用区间
const endDisableDate = (time) => {
    let beginDateVal = params.value.createStartTime
    if (beginDateVal) {
        return time.getTime() < new Date(beginDateVal).getTime()
    }
}

// 结构类型选择
const structureTypeChange = val => {
	const structureTypes = structureTypeOptions.value.find(item => item.value === val);
	if (structureTypes) {
		params.value.structureType1 = '';
		structureType1Options.value = structureTypes.children;
	}
};
// 用途选择
const useChange = (val) => {
    const use = useOptions.value.find(item => item.value === val)
    if (use) {
		params.value.purpose1 = '';
        use1Options.value = use.children
    }
}

//表格
const multipleTableRef = ref();
// 表格多选
const handleSelectionChange = val => {
    multipleSelection.value = val || [];
    curTableRow.value = val[0];
};
// 表格行点击事件
const rowClick = (row, column, event) => {
    if (multipleTableRef.value) {
        // 设置选中效果
        multipleTableRef.value.toggleRowSelection(row);
    }
};

// 分页
// 每页显示多少行
const handleSizeChange = val => {
    // 改变每页显示的条数
    queryPagination.value.pageSize = val;
    // 注意：在改变每页显示的条数时，要将页码显示到第一页
    queryPagination.value.pageNo = 1;
    onSearch();
};
// 当前页数
const handleCurrentChange = val => {
    queryPagination.value.pageNo = val;
    onSearch();
};

// 点击编号跳转至此数据的详细信息界面
const viewProject = row => {
    router.push({
        path: '/buildingVulnerAnalysis/statisticalAnalysis/highriseBuildingState/highriseDetailsInterface',
        // 路由参数
        query: { chbpiId: row.chbpiId,isView:true }
    });
};
// 获取选中行中的id组成新的数组
function purgetArrayIds() {
    let arrIds = [];
    // 判断是否有选中行
    if (multipleSelection.value && multipleSelection.value.length) {
        // 遍历获取id
        multipleSelection.value.map((item, index) => {
            arrIds.push(item.chbpiId);
        });
    }
    return arrIds;
}

// 重新计算
const onRecalculate = () => {
    // 判断是否有选中行
    if (multipleSelection.value && multipleSelection.value.length) {
        const arrIds = purgetArrayIds();
        // 加载遮罩
        proxy.$modal.loading();
        //计算
        highriseCalculationApi({
            chbpiIds: arrIds.join(',')
        }).then(res => {
            // 关闭遮罩层
            proxy.$modal.closeLoading();
            if (res.code == 200 && res.data) {
                proxy.$modal.msgSuccess('计算完成！');
                // 重载表格
                onSearch();
            } else {
                proxy.$modal.msgWarning('计算失败！');
            }
        }).catch(err => {
            // 关闭遮罩层
            proxy.$modal.closeLoading();
            console.log(err);
        });
    } else {
        proxy.$modal.msgWarning('请选择行进行计算！');
    }
};
// 导出
const onExport = () => {
    // 判断是否有选中行
    if (multipleSelection.value && multipleSelection.value.length) {
        const arrIds = purgetArrayIds();
        // 方式1：通用方法
        // proxy.download('/fshBuildings/importFshBuildings?chbpiIds=' + arrIds.join(','), null, '高层建筑破坏状态数据.xlsx', 'get');

        // 方式2：自定义下载
        // 逗号隔开的id值
        highriseExportApi({ chbpiIds: arrIds.join(',') }).then(res => {
            if (res) {
                downloadFile(res, '高层建筑破坏状态数据.xlsx')
            } else {
                proxy.$modal.msgError('导出高层建筑破坏状态数据失败！');
            }
        }).catch(err => {
            proxy.$modal.msgError(err || '导出高层建筑破坏状态数据失败！');
        });
    } else {
        proxy.$modal.msgWarning('请选择行进行导出！');
    }
};
// 查看计算结果
const onViewResults = () => {
    // 判断是否有选中行
    if (multipleSelection.value && multipleSelection.value.length == 1) {
        // 跳转详情页
        viewProject(multipleSelection.value[0]);
    } else if (multipleSelection.value && multipleSelection.value.length > 1) {
        proxy.$modal.msgWarning('请选择一行数据进行查看！');
    } else {
        proxy.$modal.msgWarning('请选择行进行计算！');
    }
};
// 查询
const onSearch = () => {
    const query = {
        ...params.value,
        page: queryPagination.value.pageNo,
        rows: queryPagination.value.pageSize
    }
    queryHighriseApi(query).then((res) => {
        if (res.code === 200 && res.data) {
            // 分页总数
            queryPagination.value.total = res.data.total;
            tableData.value = res.data.rows.length ? res.data.rows : [];
        } else {
            // 分页总数
            queryPagination.value.total = 0;
            tableData.value = [];
        }
    }).catch(err => {
        console.log(err);
    });
};
//重置
const onRest = () => {
    proxy.resetForm("queryRef")
    // 只有一个结构类型，默认选中
	if(structureTypeOptions.value?.length) {
		params.value.structureType = structureTypeOptions.value[0].value || '';
        // 结构类型选择
        structureTypeChange(params.value.structureType);
	}
    onSearch();
};
//导入
const onImport = () => {
    router.push({ path: '/disasterDataManagement/importData/buildingDamageData' })
}

// //修改
// const onModify = (row) => {
//     router.push({ path: '', query: { id: 'modify', type: row.type } })
// }
// //删除
// const onDelete = (row) => {
//     const query = { number: row.number }
//     deleteBuildingsById(query).then((res) => {
//         if (res.code === 200) {
//             console.log(res)
//             proxy.$modal.msgSuccess("删除成功");
//             onSearch();
//         }
//     }).catch(err => {
//         console.log(err);
//     })
// }

// 挂载完成
onMounted(() => {
	// 只有一个结构类型，默认选中
	if(structureTypeOptions.value?.length) {
		params.value.structureType = structureTypeOptions.value[0].value || '';
        // 结构类型选择
        structureTypeChange(params.value.structureType);
	}
    // 初始化获取数据
    onSearch();
    // 获取行政区划数据
    getProvinceData();
});
</script>
 
<style lang="scss">
.table-wrapper {
    position: relative;

    h4 {
        font-size: 16px;
        font-weight: bold;
        color: #107ce5;
        text-align: center;
    }
}

.paging {
    padding: 20px 0;
}

.form-inline {
    .el-form-item {
        margin-right: 0;
    }
}
</style>


